package com.chipcoo.shiro.authc;

import com.chipcoo.UserPrincipal;
import com.chipcoo.utils.BeanUtils;
import com.chipcoo.utils.SecurityUtils;
import com.chipcoo.ResponseResult;
import com.chipcoo.web.utils.MediaTypeUtils;
import com.chipcoo.utils.ValidateUtils;
import com.chipcoo.web.utils.WebUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.util.PathMatcher;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public final class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.FormAuthenticationFilter {
    @Override
    protected boolean isLoginSubmission(ServletRequest request, ServletResponse response) {
        boolean ret =  super.isLoginSubmission(request, response);
        if(ret){
            if(!ValidateUtils.isCaptchaValidated(request))
            {
                ret= false;
            }
        }
        return ret;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token,
                                     AuthenticationException e, ServletRequest request, ServletResponse response) {
        int errCode = SecurityUtils.parseLoginErr(e);
        request.setAttribute(getFailureKeyAttribute(), errCode);
        SecurityUtils.increaseSessionError();
        return true;
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        SecurityUtils.resetSessionError();

        if(request instanceof HttpServletRequest){
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;

            String loginName = token.getPrincipal().toString();
            //region 写入COOKIE
            Cookie[] cookies = httpServletRequest.getCookies();
            boolean shouldWriteLoginName, shouldWriteUID;
            shouldWriteLoginName=shouldWriteUID=true;

            int userID= ((UserPrincipal)subject.getPrincipal()).getUserID();
            String uidCode = com.chipcoo.utils.StringUtils.i2radix64(userID);

            if(null!=cookies){
                for(int i=0;i<cookies.length;i++){
                    if( cookies[i].getName().equals("loginName") ){
                        if( cookies[i].getValue().equalsIgnoreCase(loginName) ){
                            shouldWriteLoginName=false;
                            break;
                        }
                    }else if( cookies[i].getName().equals("uid") ){
                        if( cookies[i].getValue().equals(uidCode) ){
                            shouldWriteLoginName= false;
                            break;
                        }
                    }
                }
            }
            if(shouldWriteLoginName)
                WebUtils.setCookie( ((HttpServletResponse) response),"loginName",loginName,Integer.MAX_VALUE);
            if(shouldWriteUID)
                WebUtils.setCookie( ((HttpServletResponse) response),"uid", uidCode,Integer.MAX_VALUE);
            //endregion
        }

        return true;
        /*if( MediaTypeUtils.isAjax((HttpServletRequest) request) ) return true;
        else return super.onLoginSuccess(token, subject, request, response);*/
    }

    @Override
    protected boolean pathsMatch(String pattern, String path) {
        return BeanUtils.getBean("pathMatching", PathMatcher.class).match(pattern,path);
    }


    @Override
    protected void issueSuccessRedirect(ServletRequest request,
                                        ServletResponse response) throws Exception {
        /*String successUrl= WebUtils.getString(request,"returnUrl");
        org.apache.shiro.web.util.WebUtils.issueRedirect(request, response, StringUtils.isBlank(successUrl)?getSuccessUrl():successUrl, null,StringUtils.isBlank(successUrl));*/

    }
}
